package com.ocom.mysql;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.baomidou.mybatisplus.autoconfigure.MybatisPlusAutoConfiguration;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


@Configuration
@AutoConfigureBefore(value = {DruidDataSourceAutoConfigure.class, MybatisPlusAutoConfiguration.class})
public class DataSourceConfig {

    @Bean(name = "defaultDataSource")
    @ConfigurationProperties("spring.datasource.druid.master")
    public DataSource defaultDataSource() {
        return DruidDataSourceBuilder.create().build();
    }

    @Bean(name = "defaultDataSourceSlave")
    @ConfigurationProperties("spring.datasource.druid.slave")
    public DataSource defaultDataSourceSlave() {
        return DruidDataSourceBuilder.create().build();
    }

    @Bean("dynamicDS")
    @Primary
    public DynamicDataSource dataSource() {
        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        Map<Object, Object> dsMap = new ConcurrentHashMap<>();
        //1个总库主从  1个分库主从
        dsMap.put("defaultDataSource", defaultDataSource());
        dsMap.put("defaultDataSourceSlave", defaultDataSourceSlave());
        dynamicDataSource.setTargetDataSources(dsMap);
        return dynamicDataSource;
    }

    //事务管理器DataSourceTransactionManager构造参数需要DataSource
    //这里可以看到我们给的是dynamicDS这个bean
    @Bean
    public PlatformTransactionManager transactionManager() {
        return new DataSourceTransactionManager(dataSource());
    }


}

